package com.yusong.algorithm.array;


/**
 * 3. 无重复字符的最长子串
 */
public class TwoPoint3 {

    public static void main(String[] args) {
        String source = "abcdefg";
        TwoPoint3 main = new TwoPoint3();
        System.out.println(main.lengthOfLongestSubstring(source));
    }


    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() == 0){
            return 0;
        }


        char[] array = s.toCharArray();
        int length = array.length;
        int leftIndex = 0;
        //
        int rightIndex = -1;
        int maxLength = 0;
        // ASCII码：一个字节8位 256中状态
        boolean[] showFlag = new boolean[256];

        while (leftIndex < length){
            //不断移动右指针，直到要遇到重复
            while (rightIndex < length -1){
                int nextRight = rightIndex+1;
                int nextRightValue = array[nextRight];
                if(showFlag[nextRightValue]){
                    //遇到重复
                    break;
                }
                rightIndex = nextRight;
                showFlag[nextRightValue] = true;
            }
            int currentLength = rightIndex - leftIndex +1;
            maxLength = Math.max(maxLength, currentLength);
            if(maxLength == length){
                break;
            }else {
                int leftValue = array[leftIndex];
                showFlag[leftValue] = false;
                leftIndex++;
            }

        }

        return maxLength;
    }
}
